package com.queue.lock;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 阻塞队列的简单实现
 *
 * @author: chenhs
 * @date: Created in 11:01 2019/10/11
 **/
public class MyBlockingQueue<E> {
    /**
     * 阻塞队列的最大容量
     */
    int size;

    ReentrantLock lock = new ReentrantLock();
    /**
     * 队列底层实现
     */
    LinkedList<E> list = new LinkedList<>();

    /**
     * 队列满时的等待条件
     */
    Condition notFull = lock.newCondition();
    /**
     * 队列空时的等待条件
     */
    Condition notEmpty = lock.newCondition();

    public MyBlockingQueue(int size) {
        this.size = size;
    }

    public void enqueue(E e) throws InterruptedException {
        lock.lock();

        try {
            //队列已满，在notFull条件上等待
            while (list.size() == size) {
                notFull.await();
            }
            //入队：加入链表末尾
            list.add(e);
            System.out.println("入队：" + e);
            //通知在notEmpty条件上等待的线程
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }


    public E dequeue() throws InterruptedException {
        E e;
        lock.lock();

        try {
            //队列为空，在notEmpty上等待
            while (list.size() == 0) {
                notEmpty.await();
            }
            //出队：移除链表首元素
            e = list.removeFirst();
            System.out.println("出队：" + e);
            //通知在notNull条件上等待的线程
            notFull.signal();
            return e;
        } finally {
            lock.unlock();
        }
    }


}
